package MapReduce.Demo9_Grouping_Gender;

import MapReduce.writableBean.GenderWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import utils.JobSubmit;

import java.io.IOException;

/**
 * @Author lixinlei
 * @Date 2023/3/21 11:06
 */
public class GenderApp {

    public static class GenderMapper extends Mapper<LongWritable,Text, GenderWritable, Text>{

        GenderWritable outKey = new GenderWritable();
        Text outValue = new Text();

        @Override
        protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, GenderWritable, Text>.Context context) throws IOException, InterruptedException {

            String line = value.toString();

            String[] fields = line.split("\t");

            outKey.setGroupName(fields[0]);
            outKey.setPersonName(fields[1]);
            outKey.setAge(Integer.parseInt(fields[2]));

            outValue.set(fields[3]);

            context.write(outKey,outValue);

        }
    }

    public static class GenderReducer extends Reducer<GenderWritable,Text,GenderWritable, Text>{

        Text outValue = new Text();

        @Override
        protected void reduce(GenderWritable key, Iterable<Text> values, Reducer<GenderWritable, Text, GenderWritable, Text>.Context context) throws IOException, InterruptedException {

            int boyCount = 0;
            int girlCount = 0;

            for (Text value : values) {
                String gender = value.toString();
                if(gender.equals("男")){
                    boyCount += 1;
                }else{
                    girlCount += 1;
                }
            }

            outValue.set("男："+boyCount+",女："+girlCount);

            context.write(key,outValue);

        }
    }

    public static void main(String[] args) {
        JobSubmit.submitBaseJob(
                GenderApp.class,
                args,
                "group",
                GenderGroupingComparator.class,
                "sort",
                GenderSortComparator.class
        );
    }

}
